package cn.edu.scau.cmi.chenyuanying.orm.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.chenyuanying.orm.domain.Student;

public class StudentDAO extends BaseDAO{
	public void add(Student s) {
		Session session = getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(s);
			tx.commit();
		} catch(RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}				
	}
	
	public void update(Student s) {		
		Session session = getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			String hql = "update Student s set s.name=:name, s.tutor=:tutor where s.id=:id";
			Query<Student> query = session.createQuery(hql);
			query.setParameter("name", s.getName());
			query.setParameter("tutor", s.getTutor());
			query.setParameter("id", s.getId());
			
			query.executeUpdate();
			tx.commit();
		} catch(RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	public void delete(int id) {
		Session session = getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Object s = session.get(Student.class, id);
			session.delete(s);
			tx.commit();
		} catch(RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	public List<Student> findAll() {
		Session session = getSession();
		List<Student> list = null;
		try {
			String hql = "from Student";
			@SuppressWarnings("unchecked")
			Query<Student> query = session.createQuery(hql);
			list = query.list();
		} catch(RuntimeException e) {
			throw e;
		} finally {
			session.close();
		}
		return list;
	}
	
	public List<Student> findByProperty(String property, String value) {
		Session session = getSession();
		List<Student> list = null;
		try {
			String hql = "from Student where " + property + "= '" + value + "'";
			@SuppressWarnings("unchecked")
			Query<Student> query = session.createQuery(hql);
			list = query.list();
		} catch(RuntimeException e) {
			throw e;
		} finally {
			session.close();
		}
		return list;
	}
}
